« Blinkin' PIC | Main | A bigger basic H-bridge »

Digital Input to the PIC16F628 in C (March 26, 2005)

I recently mentioned that I could not convince C to read from PORTA of a PIC. I have seen the error of my ways. The only thing missing from my code was a single line to disable analog functions on PORTA. inserting CMCON = 0x07; into the top of main() nicely fixed the mysterious I/O failures.

With the aforementioned knowledge, the final version of the C code for the counting PIC program is below, it is now functionally identical to the JAL version previously posted. The compiler creates an astonishly small 75 words/instructions of program code from this and uses only 6 bytes of RAM (or file registers for the Microchip inclined).


#include <pic.h> #define PORTBIT(adr, bit) ((unsigned)(&adr)*8+(bit)) static bit hl @ PORTBIT (PORTA, 2); main (void) { unsigned char i, j, k; char ud = 0; char high_low; CMCON = 0x07; /* disable analog functions on PORTA */ TRISB = 0; /* all bits output */ TRISA = 0 b00000100; /* 3rd bit as input all others output */ j = 0; for (;;) { high_low = hl; if (high_low) PORTB = j; for (i = 255; --i;) for (k = 64; --k;) { if ((k & 0 b111) == 0 b111) { /* LEDs on */ if (!high_low) PORTB = j; PORTA = (ud) | (((!ud) << 1) & 0 b10); } else { /* LEDs off */ if (!high_low) PORTB = 0; PORTA = 0; } } if (j == 0) ud = 1; if (j == 0xFF) ud = 0; if (ud) j++; else j--; } }

It should also be mentioned, that PICC Lite doesn't know about the 16f628 and treats in like it's smaller sibling, the 16f627. So, if you're using PICC Lite and you want to use a 16f62x class chip, you might as well save some cash and buy 16f627 chips.


Posted by spiffed at March 26, 2005 12:46 PM